package com.zzvcom.sms.entity;

import com.zzvcom.sms.exception.AppParamException;
import com.zzvcom.sms.sign.Signable;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.TreeMap;

public abstract class AppParam implements Signable {
    private final String companyCode;
    private final String appKey;

    /**
     * 秒级 时间戳
     */
    private final Long timestamp;

    /**
     * 8 位随机数
     */
    private final String nonce;

    public AppParam(String appKey, String companyCode, Long timestamp, String nonce) {
        if (StringUtils.isBlank(appKey)) {
            throw new AppParamException("appKey参数不存在");
        } else if (StringUtils.isBlank(companyCode)) {
            throw new AppParamException("企业代码参数不存在");
        } else if (timestamp == null) {
            throw new AppParamException("时间戳参数不存在");
        } else if (timestamp.toString().length() != Constants.SECOND_TIMESTAMP_LEN) {
            throw new AppParamException("时间戳参数不正确, 时间戳参数是秒级时间戳");
        } else if (StringUtils.isBlank(nonce)) {
            throw new AppParamException("随机字符串参数不存在");
        } else if (nonce.length() != Constants.NONCE_LEN) {
            throw new AppParamException("随机字符串参数的长度不正确");
        } else {
            this.appKey = appKey;
            this.companyCode = companyCode;
            this.timestamp = timestamp;
            this.nonce = nonce;
        }
    }

    public Map<String, String> toMap() {
        Map<String, String> treeMap = new TreeMap<>();
        treeMap.put("appKey", this.appKey);
        treeMap.put("companyCode", this.companyCode);
        treeMap.put("timestamp", Long.toString(this.timestamp));
        treeMap.put("nonce", this.nonce);
        return treeMap;
    }

}
